package com.example.demo.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ImageUtil
 *
 * @author LBX
 * @date 2020/11/17 9:22
 */
public class ImageUtil {
    public static void main(String[] args) {
        File file = new File("/Users/libingxing/Desktop/svn/20190621JSQWeb/D:");
        listAndResize(file);
    }

    public static void listAndResize(File dir) {
        if (dir.exists() && dir.isDirectory()) {
            File[] uploads = dir.listFiles();
            if (uploads == null) {
                return;
            }
            for (File upload : uploads) {
                if (upload.isDirectory()) {
                    listAndResize(upload);
                }
//                        根目录
                if (upload.isFile()) {
                    reSize(upload, upload, 1000, 1000, true);
                }
            }
        }
    }

    /**
     * @param srcImg     原图片
     * @param destImg    目标位置
     * @param width      期望宽
     * @param height     期望高
     * @param equalScale 是否等比例缩放
     */
    public static void reSize(File srcImg, File destImg, int width,
                              int height, boolean equalScale) {
        String type = getImageType(srcImg);
        if (type == null) {
            return;
        }
        switch (type) {
            case "jpg":
            case "png":
            case "JPG":
            case "jpeg":
                break;
            default:
                return;
        }
        if (width < 0 || height < 0) {
            return;
        }
        BufferedImage srcImage;
        try {
            srcImage = ImageIO.read(srcImg);
            if (srcImage.getWidth() < 1000 && srcImage.getHeight() < 1000) {
                return;
            }
            System.out.println("srcImg size=" + srcImage.getWidth() + "X" + srcImage.getHeight());
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        // targetW，targetH分别表示目标长和宽
        BufferedImage target;
        width = (int) (0.3 * srcImage.getWidth());
        height = (int) (0.3 * srcImage.getHeight());
        if (width < 1000) {
            width = 1000;
        }
        if (height < 1000) {
            height = 1000;
        }
        double sx = (double) width / srcImage.getWidth();
        double sy = (double) height / srcImage.getHeight();
        // 等比缩放
        if (equalScale) {
            if (sx > sy) {
                sx = sy;
                width = (int) (sx * srcImage.getWidth());
            } else {
                sy = sx;
                height = (int) (sy * srcImage.getHeight());
            }
        }
        System.out.println("destImg size=" + width + "X" + height);
        ColorModel cm = srcImage.getColorModel();
        WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();

        target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        Graphics2D g = target.createGraphics();
        // smoother than exlax:
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(srcImage, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        // 将转换后的图片保存
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(target, type, baos);
            FileOutputStream fos = new FileOutputStream(destImg);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件后缀不带.
     *
     * @param file 文件后缀名
     */
    private static String getImageType(File file) {
        if (file != null && file.exists() && file.isFile()) {
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index != -1 && index < fileName.length() - 1) {
                return fileName.substring(index + 1);
            }
        }
        return null;
    }
}
